<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import {
  IconPlay,
  IconHeart,
  IconBookmark,
  IconBookmarkFilled,
} from "@/components/icons";
import CommentSection from "@/components/CommentSection.vue";
import Navbar from "@/components/Navbar.vue";
import { useArtistAPI } from "@/services/artist";
const artistAPI = useArtistAPI();
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();
import SongList from "@/components/SongList.vue";
import { useCommentAPI } from "@/services/comment";
const commentAPI = useCommentAPI();
import { usePlayerStore } from "@/stores/player";
const playerStore = usePlayerStore();

const artistInfo = ref({
  name: "",
  avatar: "",
  fans: 0,
  creationCount: 0,
  description: "暂无介绍",
  joinDate: "2023年12月",
  songs: [],
});

const comments = ref([]); // 替换原有的静态评论数据

const tabs = [
  { id: "songs", name: "创作音乐" },
  { id: "comments", name: "评论" },
];

const activeTab = ref(tabs[0]);
const isFollowed = ref(false);
const loading = ref(true);

const toggleFollow = () => {
  isFollowed.value = !isFollowed.value;
};

const route = useRoute();

// 获取歌手详情
const fetchArtistInfo = async () => {
  loading.value = true;
  try {
    const uid = route.params.id as string;
    // 并行获取歌手信息、评论和歌曲
    const [artistRes, commentRes] = await Promise.all([
      artistAPI.getArtistDetail(uid),
      commentAPI.getCommentBySingerId(uid),
    ]);

    if (artistRes.code === 200) {
      const data = artistRes.data;
      artistInfo.value = {
        name: data.uname,
        avatar: data.avatarUrl || userStore.defaultAvatarUrl,
        fans: 0,
        creationCount: 0,
        description: data.description || "暂无介绍",
        joinDate: "2023年12月",
        songs: [],
      };

      // 获取歌手的歌曲
      const songsRes = await artistAPI.getSingerSongs(data.uname);
      console.log(songsRes.data);
      if (songsRes.code === 200) {
        console.log(songsRes.data);
        const songs = songsRes.data.map((item: any) => ({
          id: item.musicId,
          name: item.musicName,
          artist: item.musicAuthor,
          typeId: item.musicTypeId,
          url: item.musicUrl,
          cover: item.musicCoverUrl,
          length: item.musicLength,
          status: item.status,
          score: item.musicAverageScore,
          lyric: item.lyric,
          isFavorite: item.favorStatus,
        }));
        artistInfo.value.songs = songs || [];
        artistInfo.value.creationCount = songsRes.data.length || 0;
      }
    }

    if (commentRes.data) {
      comments.value = commentRes.data;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 刷新评论列表
const refreshComments = async () => {
  try {
    const { data } = await commentAPI.getCommentBySingerId(
      route.params.id as string
    );
    if (data) {
      comments.value = data;
    }
  } catch (error) {
    console.error("获取评论失败:", error);
  }
};

// 添加播放全部处理函数
const handlePlayAll = () => {
  if (artistInfo.value.songs.length > 0) {
    // 获取第一首歌
    const firstSong = artistInfo.value.songs[0];
    // 播放第一首歌并设置整个歌单作为播放列表
    playerStore.playSong(firstSong, artistInfo.value.songs);
  }
};

onMounted(() => {
  fetchArtistInfo();
});
</script>

<template>
  <div class="p-5">
    <div v-if="loading" class="flex justify-center items-center min-h-screen">
      <div class="text-gray-600">加载中...</div>
    </div>

    <div v-else>
      <!-- 头部个人信息 -->
      <div class="flex gap-8 mb-10">
        <div class="shrink-0">
          <img
            :src="artistInfo.avatar"
            alt="音乐人头像"
            class="w-48 h-48 rounded-full object-cover"
          />
        </div>
        <div class="flex-1">
          <h1 class="text-3xl font-bold">{{ artistInfo.name }}</h1>
          <div class="mt-4 flex items-center gap-4">
            <button
              @click="handlePlayAll"
              class="h-10 flex items-center gap-2 px-4 bg-gray-200 text-gray-900 rounded hover:bg-gray-200"
            >
              <IconPlay class="w-5 h-5" />
              <span class="text-sm font-semibold">播放音乐人</span>
            </button>
            <button
              @click="toggleFollow"
              class="h-10 flex items-center gap-2 px-4 bg-gray-200 rounded"
            >
              <component
                :is="isFollowed ? IconBookmarkFilled : IconBookmark"
                class="w-5 h-5"
              />
            </button>
            <div class="flex flex-col items-start">
              <span class="text-xs text-gray-600">听众</span>
              <span class="text-2xl font-bold text-gray-800 font-family">{{
                artistInfo.fans
              }}</span>
            </div>
            <div class="flex flex-col items-start">
              <span class="text-xs text-gray-600">创作数量</span>
              <span class="text-2xl font-bold text-gray-800 font-family">{{
                artistInfo.creationCount
              }}</span>
            </div>
          </div>
          <p class="text-sm text-gray-500 mt-2">
            加入于 {{ artistInfo.joinDate }}
          </p>
          <p class="mt-4 text-gray-900 text-sm">{{ artistInfo.description }}</p>
        </div>
      </div>

      <!-- 导航栏 -->
      <div class="mt-8">
        <Navbar :items="tabs" v-model="activeTab" />
      </div>

      <!-- 内容区域 -->
      <div class="mt-6">
        <!-- 创作歌曲 -->
        <div v-show="activeTab.id === 'songs'">
          <SongList :songs="artistInfo.songs" :show-header="false" />
        </div>

        <!-- 评论区 -->
        <div v-show="activeTab.id === 'comments'" class="mt-6">
          <CommentSection
            :comments="comments"
            :singer-id="route.params.id as string"
            @comment-added="refreshComments"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:deep(.el-table) {
  --el-table-border-color: transparent;
  --el-table-bg-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-hover-bg-color: #f9fafb;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  border-bottom: none;
}

:deep(.el-table__row) {
  border-radius: 8px;
}
</style>
